<script setup lang="ts">
import {computed, onMounted, type PropType, ref} from "vue";
import type {KeyMap} from "./types";

  const props=defineProps({
    options:{
      type:Array as PropType<any[]>,
      default:()=>[]
    },
    fieldMap:{
      type:Object as PropType<KeyMap>,
      default:()=>{
        return {
          value:'id',
          label:'name',
        }
      }
  },
  remoteApi:{
    type:Function as PropType<(query?:unknown)=>Promise<any[]|undefined>|[]|undefined>,
  },
  query:{
    type:[Object,String,Number,Array] as PropType<any|string|number|[]>,
    default:undefined,
  }
})
const useRemote=computed(()=>{
  return props.remoteApi!=undefined;
})
const ops=ref<any[]>([])
const ifLoad=async ()=>{
  if (props?.remoteApi){
    const res = await props.remoteApi(props.query);
    ops.value=res||[]
  }
}
onMounted(()=>{
  console.log('props.fieldMap',props.fieldMap)
  ifLoad()
})
</script>

<template>
  <el-select>
    <template #prefix>
      <el-button v-if="useRemote" link @click="ifLoad">刷新</el-button>
    </template>
    <template v-if="!useRemote">
      <el-option v-for="(o,i) in props.options" :key="i" :value="o[props.fieldMap.value]" :label="o[props.fieldMap.label]" />
    </template>
    <template v-else>
      <el-option v-for="o in ops" :key="o[props.fieldMap.value]" :value="o[props.fieldMap.value]" :label="o[props.fieldMap.label]" />
    </template>
  </el-select>
</template>

<style scoped lang="scss">

</style>
